package org.jeecg.modules.demo.zhidingzhouqigongzuo.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.demo.peihebumenbiao.entity.Peihebumenbiao;
import org.jeecg.modules.demo.zhidingzhouqigongzuo.entity.*;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.zhidingzhouqigongzuo.vo.YZhidingzhouqigongzuoPage;
import org.jeecg.modules.demo.zhidingzhouqigongzuo.service.IYZhidingzhouqigongzuoService;
import org.jeecg.modules.demo.zhidingzhouqigongzuo.service.IYPeihebumenbiaoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 制定周期性工作
 * @Author: jeecg-boot
 * @Date:   2025-10-27
 * @Version: V1.0
 */
@Tag(name="制定周期性工作")
@RestController
@RequestMapping("/zhidingzhouqigongzuo/yZhidingzhouqigongzuo")
@Slf4j
public class YZhidingzhouqigongzuoController {
	@Autowired
	private IYZhidingzhouqigongzuoService yZhidingzhouqigongzuoService;
	@Autowired
	private IYPeihebumenbiaoService yPeihebumenbiaoService;
	@Autowired
	private IYZhidingzhouqigongzuoService zhidingzhouqigongzuoService;
	/**
	 * 分页列表查询
	 *
	 * @param yZhidingzhouqigongzuo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "制定周期性工作-分页列表查询")
	@Operation(summary="制定周期性工作-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ZhidingzhouqiDto>> list(YZhidingzhouqigongzuo yZhidingzhouqigongzuo,
												@RequestParam(name="pageNo",defaultValue="1") Integer pageNo,
												@RequestParam(name="pageName",defaultValue = "10") Integer pageSize,
												HttpServletRequest  req){
		//获取登录用户的部门id
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departId = sysUser.getDepartIds();
		//根据部门id找到该部门对应的全部数据表
		IPage<ZhidingzhouqiDto> pagedto = new Page<>();
		Page<YZhidingzhouqigongzuo> page = new Page<YZhidingzhouqigongzuo>();
		QueryWrapper<YZhidingzhouqigongzuo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("zhuguanbumenid", departId);
		IPage<YZhidingzhouqigongzuo> pageList = zhidingzhouqigongzuoService.page(page, queryWrapper);
		List<YZhidingzhouqigongzuo> list = pageList.getRecords();
		List<ZhidingzhouqiDto> listdto = new ArrayList<>();
		//存入IPage<ZhidingzhouqiDto>中
		for(int i = 0;i<list.size();i++){
			ZhidingzhouqiDto zhidingzhouqiDto = new ZhidingzhouqiDto();
			BeanUtils.copyProperties(list.get(i), zhidingzhouqiDto);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String formattedDate = sdf.format(list.get(i).getXiacihuibaoshijian());
			zhidingzhouqiDto.setXiacihuibaoshijian(formattedDate);
			//插入配合部门id和驳回情况中状态为驳回的部门id
			String peiheid = "";
			String bohuiqingkuang = "";
			QueryWrapper<YPeihebumenbiao> queryWrapper2 = new QueryWrapper<>();
			queryWrapper2.eq("zhidingbiaoid", zhidingzhouqiDto.getId());
			List<YPeihebumenbiao> list2 = yPeihebumenbiaoService.list(queryWrapper2);
			for(int j = 0;j<list2.size();j++){
				peiheid = peiheid+list2.get(j).getPeihebumenid()+",";
				if(list2.get(j).getZhuangtai().equals("驳回")){
					bohuiqingkuang = bohuiqingkuang+list2.get(j).getPeihebumenid()+",";
				}
			}
			//去除最后一个字符串
			if(peiheid.length()>0){
				zhidingzhouqiDto.setPeihebumen(peiheid.substring(0, peiheid.length()-1));
			}
			if(bohuiqingkuang.length()>0){
				zhidingzhouqiDto.setBohuiqingkuang(bohuiqingkuang.substring(0, bohuiqingkuang.length()-1));
			}
			listdto.add(zhidingzhouqiDto);
		}
		pagedto.setRecords(listdto);
		return Result.OK(pagedto);
	}

	/**
	 *   添加
	 *
	 * @param yZhidingzhouqigongzuoPage
	 * @return
	 */
	@AutoLog(value = "制定周期性工作-添加")
	@Operation(summary="制定周期性工作-添加")
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:add")
	@PostMapping(value = "/add")
//	public Result<String> add(@RequestBody ZhidingListDto zhidingListDto) {
//		YZhidingzhouqigongzuo yZhidingzhouqigongzuo = new YZhidingzhouqigongzuo();
//		BeanUtils.copyProperties(zhidingListDto, yZhidingzhouqigongzuo);
//		zhidingzhouqigongzuoService.save(yZhidingzhouqigongzuo);
//		return Result.OK("添加成功！");
//	}
	public Result<String> add(@RequestBody ZhidingListDto zhidingListDto) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departId = sysUser.getDepartIds();
		YZhidingzhouqigongzuo yZhidingzhouqigongzuo = new YZhidingzhouqigongzuo();
		BeanUtils.copyProperties(zhidingListDto, yZhidingzhouqigongzuo);
		yZhidingzhouqigongzuo.setZhuguanbumenid(departId);
		// 调用 saveMain 方法，同时保存主表和子表数据
		zhidingzhouqigongzuoService.saveMain(yZhidingzhouqigongzuo, zhidingListDto.getPeiheneirong());
		return Result.OK("添加成功！");
	}


	 //选择责任主管
	 @GetMapping(value="/zerenzhuguanList")
	 public Result<List<SysUser>> zerenzhuguanList(){
		 List<SysUser> list =zhidingzhouqigongzuoService.getZerenzhuguanid();
		 return Result.OK(list);
	 }

	 //获取配合部门
	 @GetMapping(value="/peiheList")
	 public Result<List<SysDepart>> peiheList(){
		 List<SysDepart> list = zhidingzhouqigongzuoService.getPeihebumen();
		 return Result.OK(list);
	 }

	
	/**
	 *  编辑
	 *
	 * @param yZhidingzhouqigongzuoPage
	 * @return
	 */
	@AutoLog(value = "制定周期性工作-编辑")
	@Operation(summary="制定周期性工作-编辑")
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody YZhidingzhouqigongzuoPage yZhidingzhouqigongzuoPage) {
		YZhidingzhouqigongzuo yZhidingzhouqigongzuo = new YZhidingzhouqigongzuo();
		BeanUtils.copyProperties(yZhidingzhouqigongzuoPage, yZhidingzhouqigongzuo);
		YZhidingzhouqigongzuo yZhidingzhouqigongzuoEntity = yZhidingzhouqigongzuoService.getById(yZhidingzhouqigongzuo.getId());
		if(yZhidingzhouqigongzuoEntity==null) {
			return Result.error("未找到对应数据");
		}
		yZhidingzhouqigongzuoService.updateMain(yZhidingzhouqigongzuo, yZhidingzhouqigongzuoPage.getYPeihebumenbiaoList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "制定周期性工作-通过id删除")
	@Operation(summary="制定周期性工作-通过id删除")
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		yZhidingzhouqigongzuoService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "制定周期性工作-批量删除")
	@Operation(summary="制定周期性工作-批量删除")
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.yZhidingzhouqigongzuoService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "制定周期性工作-通过id查询")
	@Operation(summary="制定周期性工作-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<YZhidingzhouqigongzuo> queryById(@RequestParam(name="id",required=true) String id) {
		YZhidingzhouqigongzuo yZhidingzhouqigongzuo = yZhidingzhouqigongzuoService.getById(id);
		if(yZhidingzhouqigongzuo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(yZhidingzhouqigongzuo);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "配合部门通过主表ID查询")
	@Operation(summary="配合部门主表ID查询")
	@GetMapping(value = "/queryYPeihebumenbiaoByMainId")
	public Result<List<YPeihebumenbiao>> queryYPeihebumenbiaoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<YPeihebumenbiao> yPeihebumenbiaoList = yPeihebumenbiaoService.selectByMainId(id);
		return Result.OK(yPeihebumenbiaoList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param yZhidingzhouqigongzuo
    */
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YZhidingzhouqigongzuo yZhidingzhouqigongzuo) {

      // Step.1 组装查询条件查询数据
      QueryWrapper<YZhidingzhouqigongzuo> queryWrapper = QueryGenerator.initQueryWrapper(yZhidingzhouqigongzuo, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<YZhidingzhouqigongzuo> yZhidingzhouqigongzuoList = yZhidingzhouqigongzuoService.list(queryWrapper);

      // Step.3 组装pageList
      List<YZhidingzhouqigongzuoPage> pageList = new ArrayList<YZhidingzhouqigongzuoPage>();
      for (YZhidingzhouqigongzuo main : yZhidingzhouqigongzuoList) {
          YZhidingzhouqigongzuoPage vo = new YZhidingzhouqigongzuoPage();
          BeanUtils.copyProperties(main, vo);
          List<YPeihebumenbiao> yPeihebumenbiaoList = yPeihebumenbiaoService.selectByMainId(main.getId());
          vo.setYPeihebumenbiaoList(yPeihebumenbiaoList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "制定周期性工作列表");
      mv.addObject(NormalExcelConstants.CLASS, YZhidingzhouqigongzuoPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("制定周期性工作数据", "导出人:"+sysUser.getRealname(), "制定周期性工作"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("zhidingzhouqigongzuo:y_zhidingzhouqigongzuo:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<YZhidingzhouqigongzuoPage> list = ExcelImportUtil.importExcel(file.getInputStream(), YZhidingzhouqigongzuoPage.class, params);
              for (YZhidingzhouqigongzuoPage page : list) {
                  YZhidingzhouqigongzuo po = new YZhidingzhouqigongzuo();
                  BeanUtils.copyProperties(page, po);
                  yZhidingzhouqigongzuoService.saveMain(po, page.getYPeihebumenbiaoList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
